package com.happy.main.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.happy.main.pagemodel.BaseResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;

/**
 * 拦截器获取注解
 * @author xinhuan.tao
 */
public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

    /**
     * 返回json数据
     */
    protected void responseOutWithJson(HttpServletResponse response, BaseResult result) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            out.append(JSONObject.toJSONString(result));
        }
    }

    protected <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) {
        T annotation = handler.getBeanType().getAnnotation(annotationType);
        if (annotation != null) return annotation;
        return handler.getMethodAnnotation(annotationType);
    }

    protected <T extends Annotation> boolean findClassAnnotation(HandlerMethod handler, Class<T> annotationType) {
        Class<? extends Object> clazz = handler.getBean().getClass();
        Annotation[] classAnnotations = clazz.getAnnotations();
        if (null == classAnnotations || classAnnotations.length == 0) {
            return false;
        }

        for (int i = 0; i < classAnnotations.length; i++) {
            if (classAnnotations[i].annotationType() == annotationType) {
                return true;
            }
        }
        return false;
    }
}
